<!-- 分配工种弹框 列表通过，取消拒保，drawer里的添加工种都调用这个
-->
<template>
    <div>
        <el-dialog
            v-model="showDialog"
            :title="titleName"
            :width="isMobile ? '1540' : '80%'"
            top="10vh"
        >
            <div class="dialogcheckpqdwokVisibletop">
                <!-- <div class="flexbox topitem">
            <div class="area">地区</div> <el-select clearable v-model="area" filterable placeholder="请选择">
                <el-option v-for="item in provincelist" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </div> -->
                <div class="flexbox topitem">
                    <div class="area">特别约定</div>
                    <el-input
                        clearable
                        style="width: 184px"
                        v-model="tbyd"
                        placeholder="选填"
                        class="input-with-select"
                    >
                    </el-input>
                </div>
            </div>
            <div class="dialogcheckpqdwokVisiblecontent">
                <div class="lcontent">
                    <div class="ipt">
                        <el-input
                            v-model="jobtypekey"
                            @input="changevalue"
                            placeholder="请输入"
                            class="input-with-select"
                        >
                            <template #prepend>
                                <el-button :icon="Search" />
                            </template>
                        </el-input>
                    </div>
                    <div class="tabbox">
                        <div class="tab">
                            <div
                                :class="{
            tabitem: true,
            jobtabactive: jobtabflag === i,
        }"
                                @click="onChangeJobTab(i, ele.id)"
                                v-for="(ele, i) in joblist"
                                :key="i"
                            >
                                {{ ele.name }}
                            </div>
                        </div>
                        <div class="tabcontent">
                            <el-checkbox-group v-model="longjobcheckList">
                                <div class="columnflex">
                                    <el-checkbox
                                        v-show="jobtabid === ele.periodIndustryId && ele.name.includes(jobtypekey)
            "
                                        v-for="(ele, i) in jobinfolist"
                                        :key="i"
                                        :label="ele"
                                        :disabled="from === 'apply' && isExit(ele.id)"
                                    >{{
            ele.name }}<span>（{{ ele.level }}类）{{ ele.id }}</span></el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>
                <div class="rcontent">
                    <div class="topnum">
                        已选中<span class="blue">{{ longjobcheckList.length }}项</span>
                    </div>
                    <div class="jobselected">
                        <div
                            class="selectjobitem"
                            v-for="(ele, index) in longjobcheckList"
                            :key="index"
                        >
                            <img
                                src="../../../assets/image/拖动排序.png"
                                alt=""
                            />
                            <div class="jobname">
                                {{ ele.name }}<span>（{{ ele.level }}类）{{ ele.id }}</span>
                            </div>
                            <img
                                v-if="from !== 'apply' || (from == 'apply' && !isExit(ele.id))"
                                @click="onDelSelectedLongJob(index)"
                                src="../../../assets/image/图标.png"
                                alt=""
                            />
                        </div>
                    </div>
                </div>
            </div>
            <div class="dialogcheckpqdwokVisiblebtn">
                <el-button
                    class="my_cancelbtn"
                    @click="onHandelCancel"
                >取消</el-button>
                <el-button
                    class="my_btn"
                    @click="onHandelConfirm"
                >确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash'
import { ElMessage } from 'element-plus'

import { longdispatchingagencycheckapi, getlongjoblistapi } from '@/api/api'
import { updateOccupationStatus } from '@/api/longInsure/index'
import { shake } from '../../../utils/utils'
const changevalue = (e: any) => {
    shake(getlongjoblist, 1000)
}
const isMobile = ref((window as any).isMobile)

const props = defineProps({
    show: {
        type: Boolean,
        default: true,
    },
    itemDetail: {
        type: Object,
        default() {
            return {}
        },
    },
    /**
     * 弹框来自于哪里
     * pass: 通过  cancelRefuse: 取消拒保  edit: 添加工种  apply: 申请新工种
     * status的取值与来源有关
     * status  0 待审核 1 已通过 2 驳回 3拒保
     * 通过和取消拒保传 1
     * 添加工种取 后台给的值
     */
    from: {
        type: String,
        default: 'pass',
    },
})

const emits = defineEmits(['update:show', 'success'])

const showDialog = ref(false)

const tbyd = ref('')
const jobtypekey = ref('')
const jobtabflag = ref(0)
const joblist = ref<any>([])
const longjobcheckList = ref<any>([])
const jobtabid = ref(0)
const jobinfolist = ref<any>([])
const longservicecompanystatus = ref(0)
const hasSetCheckList = ref([]) //后端返回的已选择的工种

/**
 * 获取工种列表
 */
const getlongjoblist = async () => {
    const res: any = await getlongjoblistapi({
        searchText: jobtypekey.value,
        pageNum: 1,
        pageSize: 9999,
    })
    console.log(res, '获取长期保工种列表')
    const occupationListarr: any = []
    res.rows.forEach((ele: any, index: number) => {
        occupationListarr.push(...ele.occupationList)
        jobinfolist.value = occupationListarr
    })
    res.rows.forEach((ele: any, i: any) => {
        ele.occupationList.forEach((j: any, index: any) => {
            j.insurCompanyOccupationList = null
        })
    })
    joblist.value = res.rows
    jobtabid.value = res.rows[0].id
}

/**
 * 切换行业显示对应工种
 */
const onChangeJobTab = (i: number, id: number) => {
    console.log(id, 'id')
    jobtabflag.value = i
    jobtabid.value = id
}

/**
 * 取消勾选的工种
 * @param i
 */
const onDelSelectedLongJob = (i: number) => {
    longjobcheckList.value.splice(i, 1)
}

const onHandelCancel = () => {
    showDialog.value = false
    longjobcheckList.value = []
    tbyd.value = ''
    jobtypekey.value = ''
}

const onHandelConfirm = async () => {
    if (props.from === 'apply') {
        console.log(111, props.itemDetail)
        console.log(222, longjobcheckList.value, hasSetCheckList.value)

        if (longjobcheckList.value.length <= hasSetCheckList.value.length) {
            ElMessage.error('至少选择一项工种类型.')
            return
        }
        const filterId = longjobcheckList.value.map((i: any) => i.id)
        const query = {
            id: props.itemDetail.occupationRecord.id,
            status: 1,
            occupationIds: JSON.stringify(filterId),
        }
        const res = await updateOccupationStatus(query)
        ElMessage.success('申请成功')
    } else {
        if (longjobcheckList.value.length === 0) {
            ElMessage.error('至少选择一项工种类型.')
            return
        }
        const arr: any = []
        longjobcheckList.value.forEach((ele: any, i: any) => {
            arr.push(ele.id)
        })
        /**
         * status  0 待审核 1 已通过 2 驳回 3拒保
         * 通过和取消拒保传 1
         * 添加工种取 后台给的值
         *
         */
        longdispatchingagencycheck(
            1, //props.from === 'edit' ? props.itemDetail.status : 1,
            arr,
            tbyd.value
        )
    }
    emits('success')
    onHandelCancel()
}

const checkservicecompanyform = reactive({
    id: 0,
    serveCompanyName: '',
    companyId: 0,
    companyName: '',
    serveCompanyId: 0,
})

const longdispatchingagencycheck = async (
    status: any,
    occupationIds: any,
    remark: any
) => {
    const res: any = await longdispatchingagencycheckapi({
        ...checkservicecompanyform,
        status: status,
        occupationIds: JSON.stringify(occupationIds),
        remark: remark,
    })
    console.log(res)
    if (res.code === 200) {
        // getlonginsurecompanylist();
        emits('success')
        ElMessage({
            message: res.msg,
            type: 'success',
        })
    }
}

/**
 * 设置默认值
 */
const setDefaultValue = () => {
    const ele = cloneDeep(props.itemDetail)
    if (ele.occupationList) {
        ele.occupationList.forEach((ele: any, index: any) => {
            ele.periodIndustryName = null
        })
    } else {
        ele.occupationList = []
    }
    longjobcheckList.value = ele.occupationList
    hasSetCheckList.value = ele.occupationList
    tbyd.value = ele.remark
    longservicecompanystatus.value = ele.status
    checkservicecompanyform.id = ele.id
    checkservicecompanyform.companyName = ele.companyName
    checkservicecompanyform.companyId = ele.companyId
    checkservicecompanyform.serveCompanyName = ele.serveCompanyName
    checkservicecompanyform.serveCompanyId = ele.serveCompanyId
    jobtabflag.value = 0
}

/**
 * 申请新工种是已经申请的也显示，但是不能删除
 * @param id
 */
const isExit = (id: number) => {
    console.log(2121, hasSetCheckList.value, id)

    return !!hasSetCheckList.value.find((i: any) => i.id === id)
}

const titleName = computed(() => {
    return props.from === 'apply' ? '申请新工种' : '审批派遣单位'
})

watch(
    () => props.show,
    async (newval) => {
        showDialog.value = newval
        if (newval) {
            await getlongjoblist()
            setDefaultValue()
        }
    }
)

watch(showDialog, (newval) => {
    emits('update:show', newval)
})
</script>
<style lang="scss" scoped>
.dialogcheckpqdwokVisibletop {
    display: flex;
    align-items: center;

    .topitem {
        margin-right: 20px;
        align-items: center;
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        .area {
            min-width: 72px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            font-size: 12px;
        }
    }
}

.dialogcheckpqdwokVisiblecontent {
    box-sizing: border-box;
    margin-top: 16px;
    border-radius: 8px;
    display: flex;

    .lcontent {
        border: 1px solid #eaeaef;
        box-sizing: border-box;
        padding: 16px;
        border-radius: 6px;
        width: 60%;
        margin-right: 24px;

        .ipt {
            height: 30px;
        }

        .tabbox {
            margin-top: 16px;
            display: flex;

            .tab {
                width: 30%;
                height: 470px;
                overflow-y: scroll;

                .tabitem {
                    width: 100%;
                    box-sizing: border-box;
                    height: 38px;
                    line-height: 38px;
                    padding-left: 18px;
                    border-left: 2px solid #ffffff;
                    cursor: pointer;
                    font-size: 14px;
                }
            }

            .tabcontent {
                width: 70%;
                height: 470px;
                overflow-y: scroll;
                box-sizing: border-box;
                padding-left: 16px;
                font-size: 14px;
            }
        }
    }

    .rcontent {
        width: 39%;
        border: 1px solid #eaeaef;
        box-sizing: border-box;
        padding: 16px;
        border-radius: 6px;

        .jobselected {
            margin-top: 16px;
            width: 100%;
            box-sizing: border-box;
            height: 485px;
            overflow-y: scroll;

            .selectjobitem {
                margin-bottom: 15px;
                display: flex;
                align-items: center;
                width: 100%;
                box-sizing: border-box;
                padding: 6px 8px;

                .jobname {
                    flex: 1;
                    margin-left: 12px;
                    margin-right: 12px;
                    font-size: 12px;
                }
            }

            .selectjobitem:hover {
                background-color: #ebeffd;
                border-radius: 4px;
            }
        }
    }
}

.dialogcheckpqdwokVisiblebtn {
    margin-top: 32px;
    display: flex;
    align-items: center;
    justify-content: end;
}

.jobtabactive {
    background-color: #ebeffe;
    color: #3e5ff5;
    border-left: 2px solid #3e5ff5 !important;
}
</style>